package com.dc.project.service.impl;

import com.dc.common.constant.CustomConstants;
import com.dc.common.core.LoginBody;
import com.dc.common.core.LoginUser;
import com.dc.common.core.MyToken;
import com.dc.common.utils.RedisUtil;
import com.dc.common.utils.ShiroUtil;
import com.dc.common.utils.StringUtil;
import com.dc.common.vo.ResultVo;
import com.dc.project.service.AuthService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author zhuangcy
 * @date 2021/6/1
 * @description 用户登录验证接口实现类
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 表单登录
     *
     * @param loginBody
     * @return
     */
    @Override
    public ResultVo login(LoginBody loginBody) {
        String token = Objects.toString(SecurityUtils.getSubject().getSession().getId());
        SecurityUtils.getSubject().login(new MyToken(token, loginBody));
        // 只允许一个账号登录一次
        String key = CustomConstants.ACCESS_TOKEN_NAME + loginBody.getUsername();
        String oldToken = Objects.toString(redisUtil.get(key), "");
        if (StringUtil.isNotEmpty(oldToken)) {
            redisUtil.remove(CustomConstants.SHIRO_SESSION_NAME + oldToken);
        }
        redisUtil.set(key, token, CustomConstants.TOKEN_VALIDITY_PERIOD, TimeUnit.MILLISECONDS);
        return ResultVo.success().data(token);
    }

    /**
     * 登出
     *
     * @return
     */
    @Override
    public ResultVo logout() {
        LoginUser loginUser = ShiroUtil.getUserInfo();
        redisUtil.remove(CustomConstants.ACCESS_TOKEN_NAME + loginUser.getAccount());
        SecurityUtils.getSubject().logout();
        return ResultVo.success().msg("退出成功");
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @Override
    public ResultVo getUserInfo() {
        LoginUser userInfo = ShiroUtil.getUserInfo();
        return ResultVo.success().data(userInfo);
    }


}
